// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({env: cloud.DYNAMIC_CURRENT_ENV})
const xlsx = require('node-xlsx')

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log('已经开始处理')
  try {
    let { userdata } = event
    let alldata = []
    //1. 定义excel表格名
    let dataCSV = 'result.xlsx'
    let row = ['姓名','工号','部门',"生产线",'出行类型','出行方式', '是否常住',"openid","填写时间","目的地1","目的地1到达时间","目的地1离开时间","目的地2","目的地2到达时间","目的地2离开时间"
    ,"目的地3","目的地3到达时间","目的地3离开时间","目的地4","目的地4到达时间","目的地4离开时间"] //表格属性
    alldata.push(row);
    //2. 定义存储数据
    for (let key in userdata){
        let arr = []
        arr.push(userdata[key]._username);
        arr.push(userdata[key]._phonenumber);
        arr.push(userdata[key]._workshop);
        arr.push(userdata[key]._line);
        arr.push(userdata[key]._leavestyle_choose);
        arr.push(userdata[key]._leaveway_choose);
        arr.push(userdata[key]._energySelect);
        arr.push(userdata[key]._openid);
        arr.push(userdata[key]._time);
        // console.log("输出所有表单",key,userdata[key])
        for (let j in userdata[key]._options){
          arr.push(userdata[key]._options[j].value_region);
          arr.push(userdata[key]._options[j].value_time);
          arr.push(userdata[key]._options[j].value_leavetime);
          // console.log("输出所有时间位置信息",userdata[key]._options[j].value_region[1])
        }
        alldata.push(arr);
      }
    // console.log("alldata",alldata)
    //3，把数据保存到excel里
    var buffer = xlsx.build([{
      name: "hello",
      data: alldata
    }]);
    //4，把excel文件保存到云存储里
    return await cloud.uploadFile({
      cloudPath: 'leaveshanghai.xlsx',
      fileContent: buffer, //excel二进制文件
    })
   
  } catch (e) {
    console.error(e)
    return e
  }
  // return {
  //   event,
  //   openid: wxContext.OPENID,
  //   appid: wxContext.APPID,
  //   unionid: wxContext.UNIONID,
  // }
}